import React, { useEffect, useState } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Input, 
  Select, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Switch,
  Popconfirm,
  Avatar,
  Tabs,
  List,
  Upload,
  Image,
  Row,
  Col,
  InputNumber,
  Empty,
  Spin
} from 'antd';

// API基础URL配置
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api';
const SERVER_BASE_URL = API_BASE_URL.replace('/api', '');
import { useMessage } from '../../hooks/useMessage';
import { 
  UserOutlined, 
  PlusOutlined, 
  SearchOutlined, 
  EditOutlined, 
  DeleteOutlined,
  ReloadOutlined,
  DownloadOutlined,
  ClearOutlined,
  FileTextOutlined,
  DatabaseOutlined,
  CloudUploadOutlined,
  CloudDownloadOutlined,
  ContactsOutlined,
  PictureOutlined,
  UploadOutlined,
  PhoneOutlined,
  WechatOutlined,
  QrcodeOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useAuthStore } from '../../services/store';
import { 
  getLogs, 
  getBackups, 
  createBackup, 
  downloadBackup, 
  deleteBackup, 
  restoreBackup, 
  userApi,
  settingsApi,
  contactApi,
  uploadApi
} from '../../services/api';
import dayjs from 'dayjs';
import type { User, SystemLog, Backup, ContactPerson } from '../../types';

const { Search } = Input;
const { Option } = Select;
const { TextArea } = Input;

const SystemPage: React.FC = () => {
  const [form] = Form.useForm();
  const [contactForm] = Form.useForm();
  const message = useMessage();

  const { user: currentUser } = useAuthStore();
  
  const [activeTab, setActiveTab] = useState('users');
  const [loading, setLoading] = useState(false);
  
  // 用户管理状态
  const [users, setUsers] = useState<User[]>([]);
  const [userModalOpen, setUserModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [userSearchKeyword, setUserSearchKeyword] = useState('');
  const [selectedUserRole, setSelectedUserRole] = useState<string>('all');
  
  // 联系管理状态
  const [contacts, setContacts] = useState<ContactPerson[]>([]);
  const [contactModalOpen, setContactModalOpen] = useState(false);
  const [editingContact, setEditingContact] = useState<ContactPerson | null>(null);
  const [contactLoading, setContactLoading] = useState(false);
  

  
  // 数据备份状态
  const [backups, setBackups] = useState<any[]>([]);
  const [backupLoading, setBackupLoading] = useState(false);
  
  // 系统日志状态
  const [logs, setLogs] = useState<SystemLog[]>([]);
  const [logLevel, setLogLevel] = useState<string>('all');
  const [logModule, setLogModule] = useState<string>('all');
  const [logPagination, setLogPagination] = useState({ page: 1, limit: 10, total: 0 });

  // 加载用户数据
  const loadUsers = async () => {
    try {
      setLoading(true);
      const response = await userApi.getUsers();
      setUsers(response.users || []);
      message.success('用户数据加载成功');
    } catch (error) {
      message.error('加载用户数据失败');
      // console.error('Load users error:', error);
    } finally {
      setLoading(false);
    }
  };

  // 加载联系人数据
  const loadContacts = async () => {
    try {
      setContactLoading(true);
      const response = await contactApi.getContacts();
      // 转换API数据格式为组件需要的格式
      const formattedContacts = response.map(contact => ({
        id: contact.id,
        name: contact.name,
        position: contact.title || '客服专员',
        phone: contact.phone,
        wechat: contact.wechat || '',
        description: contact.description || `专业的${contact.title || '服务人员'}，为您提供优质服务。`,
        wechatQr: "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=WeChat%20QR%20code%20placeholder%20professional%20design&image_size=square"
      }));
      setContacts(formattedContacts);
      message.success('联系人数据加载成功');
    } catch (error) {
      message.error('加载联系人数据失败');
      console.error('Load contacts error:', error);
    } finally {
      setContactLoading(false);
    }
  };



  // 加载备份数据
  const loadBackups = async () => {
    try {
      setBackupLoading(true);
      const response = await getBackups();
      setBackups(response || []);
      message.success('备份数据加载成功');
    } catch (error) {
      message.error('加载备份数据失败');
      // console.error('Load backups error:', error);
    } finally {
      setBackupLoading(false);
    }
  };

  // 加载系统日志数据
  const loadLogs = async (page = 1, limit = 10) => {
    try {
      setLoading(true);
      const params = {
        page,
        limit,
        level: logLevel === 'all' ? undefined : logLevel
      };
      const response = await getLogs(params);
      const mappedLogs = (response.logs || []).map(log => ({
        ...log,
        createdAt: log.timestamp,
        level: log.level as 'info' | 'warn' | 'error' | 'debug'
      }));
      setLogs(mappedLogs);
      setLogPagination({
        page: response.page,
        limit: response.limit,
        total: response.total
      });
      message.success('系统日志加载成功');
    } catch (error) {
      message.error('加载系统日志失败');
      // console.error('Load logs error:', error);
    } finally {
      setLoading(false);
    }
  };

  // 根据当前tab加载对应数据
  const loadTabData = (tabKey: string) => {
    switch (tabKey) {
      case 'users':
        loadUsers();
        break;
      case 'contacts':
        loadContacts();
        break;

      case 'backup':
        loadBackups();
        break;
      case 'logs':
        loadLogs();
        break;
      default:
        break;
    }
  };

  // 初始化时只加载第一个tab的数据
  useEffect(() => {
    loadTabData('users');
  }, []);

  // tab切换时加载对应数据
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    loadTabData(key);
  };

  // 用户管理相关函数
  const handleAddUser = () => {
    setEditingUser(null);
    form.resetFields();
    setUserModalOpen(true);
    // 在Modal打开后设置默认值
    setTimeout(() => {
      form.setFieldsValue({
        role: 'guest',
        status: 'active'
      });
    }, 0);
  };

  const handleEditUser = (user: User) => {
    setEditingUser(user);
    form.setFieldsValue(user);
    setUserModalOpen(true);
  };

  const handleDeleteUser = (user: User) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除用户"${user.username}"吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await userApi.deleteUser(user.id);
          loadUsers();
        } catch (error) {
          message.error('删除用户失败');
        }
      }
    });
  };

  const handleSaveUser = async (values: any) => {
    try {
      setLoading(true);
      if (editingUser) {
        await userApi.updateUser(editingUser.id, values);
      } else {
        await userApi.createUser(values);
      }
      setUserModalOpen(false);
      form.resetFields();
      loadUsers();
    } catch (error) {
      message.error(editingUser ? '更新用户失败' : '创建用户失败');
    } finally {
      setLoading(false);
    }
  };

  // 联系人管理相关函数
  const handleAddContact = () => {
    if (contacts.length >= 2) {
      message.warning('最多只能添加2个联系人');
      return;
    }
    setEditingContact(null);
    contactForm.resetFields();
    setContactModalOpen(true);
  };

  const handleEditContact = (contact: ContactPerson) => {
    setEditingContact(contact);
    contactForm.setFieldsValue(contact);
    setContactModalOpen(true);
  };

  const handleDeleteContact = (contact: ContactPerson) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除联系人"${contact.name}"吗？`,
      onOk: async () => {
        try {
          await contactApi.deleteContact(contact.id);
          message.success('联系人删除成功');
          loadContacts();
        } catch (error) {
          message.error('删除联系人失败');
          console.error('Delete contact error:', error);
        }
      }
    });
  };

  const handleSaveContact = async (values: any) => {
    try {
      setContactLoading(true);
      
      if (editingContact) {
        // 更新联系人
        await contactApi.updateContact(editingContact.id, {
          name: values.name,
          position: values.position,
          phone: values.phone,
          wechat: values.wechat,
          description: values.description,
          wechatQr: values.wechatQr
        });
        message.success('联系人更新成功');
      } else {
        // 添加联系人数量验证
        if (contacts.length >= 2) {
          message.warning('最多只能添加2个联系人');
          setContactLoading(false);
          return;
        }
        // 创建新联系人
        await contactApi.createContact({
          type: 'primary',
          name: values.name,
          position: values.position,
          phone: values.phone,
          wechat: values.wechat,
          description: values.description,
          wechatQr: values.wechatQr,
          status: 'active',
          sort: contacts.length
        });
        message.success('联系人创建成功');
      }
      
      setContactModalOpen(false);
      contactForm.resetFields();
      loadContacts();
    } catch (error) {
      message.error(editingContact ? '更新联系人失败' : '创建联系人失败');
      console.error('Save contact error:', error);
    } finally {
      setContactLoading(false);
    }
  };



  // 备份管理相关函数
  const handleCreateBackup = async () => {
    try {
      setBackupLoading(true);
      const backupName = `系统备份_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}`;
      await createBackup({
        name: backupName,
        description: '手动创建的系统备份',
        tables: [] // 空数组表示备份所有表
      });
      message.success('备份任务已创建，正在后台处理');
      loadBackups();
    } catch (error) {
      message.error('创建备份失败');
    } finally {
      setBackupLoading(false);
    }
  };

  const handleDownloadBackup = async (backup: any) => {
    try {
      if (backup.status !== 'completed') {
        message.warning('备份尚未完成，无法下载');
        return;
      }
      const blob = await downloadBackup(backup.id);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${backup.name}.sql`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      message.success('备份下载成功');
    } catch (error) {
      message.error('下载备份失败');
    }
  };

  const handleDeleteBackup = (backup: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除备份"${backup.name}"吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await deleteBackup(backup.id);
          message.success('备份删除成功');
          loadBackups();
        } catch (error) {
          message.error('删除备份失败');
        }
      }
    });
  };

  const handleRestoreBackup = (backup: any) => {
    Modal.confirm({
      title: '确认恢复',
      content: `确定要恢复备份"${backup.name}"吗？此操作将覆盖当前数据，不可恢复。`,
      onOk: async () => {
        try {
          if (backup.status !== 'completed') {
            message.warning('备份尚未完成，无法恢复');
            return;
          }
          await restoreBackup(backup.id);
          message.success('数据恢复成功');
          loadBackups();
        } catch (error) {
          message.error('恢复数据失败');
        }
      }
    });
  };

  // 日志管理相关函数
  const handleExportLogs = async () => {
    try {
      message.success('日志导出成功');
    } catch (error) {
      message.error('导出日志失败');
    }
  };

  const handleClearLogs = () => {
    Modal.confirm({
      title: '确认清空',
      content: '确定要清空所有系统日志吗？此操作不可恢复。',
      onOk: async () => {
        try {
          message.success('日志清空成功');
          loadLogs();
        } catch (error) {
          message.error('清空日志失败');
        }
      }
    });
  };

  // 用户表格列定义
  const userColumns: ColumnsType<User> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text, record) => (
        <Space>
          <Avatar 
            src={record.avatar ? `${SERVER_BASE_URL}${record.avatar}` : undefined}
            icon={!record.avatar ? <UserOutlined /> : undefined}
          />
          <span>{text}</span>
        </Space>
      )
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname'
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => {
        const roleConfig = {
          admin: { color: 'red', text: '管理员' },
          guest: { color: 'blue', text: '游客' }
        };
        const config = roleConfig[role as keyof typeof roleConfig] || { color: 'default', text: role };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '激活' : '禁用'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditUser(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此用户吗？"
            onConfirm={() => handleDeleteUser(record)}
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">系统管理</h1>
        <p className="text-gray-600">管理系统用户、联系信息、轮播图和数据备份</p>
      </div>

      <Card>
        <Tabs
          activeKey={activeTab}
          onChange={handleTabChange}
          items={[
            {
              key: 'users',
              label: (
                <span>
                  <UserOutlined />
                  用户管理
                </span>
              ),
              children: (
                <div>
                  {/* 用户操作栏 */}
                  <div className="flex justify-between items-center mb-4">
                    <Space>
                      <Search
                        placeholder="搜索用户名"
                        value={userSearchKeyword}
                        onChange={(e) => setUserSearchKeyword(e.target.value)}
                        style={{ width: 200 }}
                      />
                      <Select
                        value={selectedUserRole}
                        onChange={setSelectedUserRole}
                        style={{ width: 120 }}
                      >
                        <Option value="all">全部角色</Option>
                        <Option value="admin">管理员</Option>
                        <Option value="guest">游客</Option>
                      </Select>
                    </Space>
                    <Space>
                      <Button icon={<ReloadOutlined />} onClick={() => loadUsers()}>
                        刷新
                      </Button>
                      <Button type="primary" icon={<PlusOutlined />} onClick={handleAddUser}>
                        新增用户
                      </Button>
                    </Space>
                  </div>

                  {/* 用户表格 */}
                  <Spin spinning={loading}>
                    <Table
                      columns={userColumns}
                      dataSource={users.filter(user => {
                        const matchesKeyword = !userSearchKeyword || 
                          user.username.toLowerCase().includes(userSearchKeyword.toLowerCase());
                        const matchesRole = selectedUserRole === 'all' || user.role === selectedUserRole;
                        return matchesKeyword && matchesRole;
                      })}
                      rowKey="id"
                      pagination={{
                        pageSize: 10,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total, range) => 
                          `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                      }}
                      locale={{
                        emptyText: <Empty description="暂无用户数据" />
                      }}
                    />
                  </Spin>
                </div>
              )
            },
            {
              key: 'contacts',
              label: (
                <span>
                  <ContactsOutlined />
                  联系人管理
                </span>
              ),
              children: (
                <div>
                  {/* 联系人操作栏 */}
                  <div className="flex justify-between items-center mb-4">
                    <div>
                      <h3 className="text-lg font-medium">联系人管理</h3>
                      <p className="text-gray-500">管理网站联系人信息，用于联系模态框显示</p>
                    </div>
                    <Space>
                      <Button icon={<ReloadOutlined />} onClick={() => loadContacts()}>
                        刷新
                      </Button>
                      <Button type="primary" icon={<PlusOutlined />} onClick={handleAddContact}>
                        新增联系人
                      </Button>
                    </Space>
                  </div>

                  {/* 联系人表单管理 */}
                  <Spin spinning={contactLoading}>
                    {contacts.length === 0 ? (
                      <div className="text-center py-8">
                        <Empty 
                          description="暂无联系人数据" 
                          image={Empty.PRESENTED_IMAGE_SIMPLE}
                        >
                          <Button type="primary" icon={<PlusOutlined />} onClick={handleAddContact}>
                            添加第一个联系人
                          </Button>
                        </Empty>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {contacts.map((contact, index) => (
                          <Card 
                            key={contact.id}
                            className="border border-gray-200 hover:border-blue-300 transition-colors"
                            styles={{ body: { padding: '16px' } }}
                          >
                            <div className="flex items-start justify-between">
                              <div className="flex items-start space-x-4 flex-1">
                                <Avatar 
                                  size={64} 
                                  src={contact.avatar} 
                                  icon={<UserOutlined />}
                                  className="border-2 border-gray-100"
                                />
                                <div className="flex-1">
                                  <div className="flex items-center space-x-2 mb-2">
                                    <h4 className="text-lg font-medium text-gray-900 mb-0">{contact.name}</h4>
                                    <Tag color="blue">联系人 {index + 1}</Tag>
                                  </div>
                                  <div className="space-y-1 text-sm">
                                    <div className="flex items-center text-gray-600">
                                      <UserOutlined className="mr-2" />
                                      <span>{contact.position}</span>
                                    </div>
                                    <div className="flex items-center text-gray-600">
                                      <PhoneOutlined className="mr-2" />
                                      <span>{contact.phone}</span>
                                    </div>
                                    {contact.wechat && (
                                      <div className="flex items-center text-gray-600">
                                        <WechatOutlined className="mr-2" />
                                        <span>{contact.wechat}</span>
                                      </div>
                                    )}
                                    {contact.description && (
                                      <div className="text-gray-500 mt-2">
                                        {contact.description}
                                      </div>
                                    )}
                                  </div>
                                </div>
                              </div>
                              <div className="flex space-x-2">
                                <Button 
                                  type="text" 
                                  icon={<EditOutlined />} 
                                  onClick={() => handleEditContact(contact)}
                                  className="text-blue-600 hover:text-blue-700"
                                >
                                  编辑
                                </Button>
                                <Button 
                                  type="text" 
                                  danger 
                                  icon={<DeleteOutlined />} 
                                  onClick={() => handleDeleteContact(contact)}
                                >
                                  删除
                                </Button>
                              </div>
                            </div>
                          </Card>
                        ))}
                        
                        {/* 添加联系人提示 */}
                        {contacts.length < 2 && (
                          <Card 
                            className="border-2 border-dashed border-gray-300 hover:border-blue-400 transition-colors cursor-pointer"
                            styles={{ body: { padding: '24px' } }}
                            onClick={handleAddContact}
                          >
                            <div className="text-center text-gray-500">
                              <PlusOutlined className="text-2xl mb-2" />
                              <div>添加第{contacts.length + 1}个联系人</div>
                              <div className="text-xs mt-1">最多可添加2个联系人</div>
                            </div>
                          </Card>
                        )}
                        
                        {/* 联系人数量提示 */}
                        <div className="text-center text-gray-500 text-sm">
                          已添加 {contacts.length}/2 个联系人
                        </div>
                      </div>
                    )}
                  </Spin>
                </div>
              )
            },
            {
              key: 'backup',
              label: (
                <span>
                  <DatabaseOutlined />
                  数据备份
                </span>
              ),
              children: (
                <div>
                  {/* 备份操作 */}
                  <div className="flex justify-between items-center mb-4">
                    <div>
                      <h3 className="text-lg font-medium">数据备份管理</h3>
                      <p className="text-gray-500">创建和管理系统数据备份</p>
                    </div>
                    <Space>
                      <Button icon={<ReloadOutlined />} onClick={() => loadBackups()}>
                        刷新
                      </Button>
                      <Button 
                        type="primary" 
                        icon={<CloudUploadOutlined />} 
                        onClick={handleCreateBackup}
                        loading={backupLoading}
                      >
                        创建备份
                      </Button>
                    </Space>
                  </div>

                  {/* 备份列表 */}
                  <Spin spinning={backupLoading}>
                    <List
                      dataSource={backups}
                      locale={{
                        emptyText: <Empty description="暂无备份数据" />
                      }}
                      renderItem={(backup, index) => {
                        return (
                          <List.Item key={backup.filename || index}>
                            <List.Item.Meta
                              avatar={<DatabaseOutlined style={{ fontSize: '24px', color: '#1890ff' }} />}
                              title={backup.name}
                              description={
                                <Space>
                                  <span>大小: {backup.fileSize ? (backup.fileSize / 1024 / 1024).toFixed(2) + ' MB' : '计算中...'}</span>
                                  <span>创建时间: {dayjs(backup.createdAt).format('YYYY-MM-DD HH:mm:ss')}</span>
                                  <Tag color={backup.status === 'completed' ? 'green' : backup.status === 'failed' ? 'red' : 'orange'}>
                                    {backup.status === 'completed' ? '已完成' : backup.status === 'failed' ? '失败' : '进行中'}
                                  </Tag>
                                  {backup.description && <span>{backup.description}</span>}
                                </Space>
                              }
                            />
                            <Space>
                              <Button 
                                icon={<CloudDownloadOutlined />} 
                                onClick={() => handleDownloadBackup(backup)}
                                disabled={backup.status !== 'completed'}
                              >
                                下载
                              </Button>
                              <Button 
                                icon={<ReloadOutlined />} 
                                onClick={() => handleRestoreBackup(backup)}
                                disabled={backup.status !== 'completed'}
                              >
                                恢复
                              </Button>
                              <Button 
                                danger 
                                icon={<DeleteOutlined />} 
                                onClick={() => handleDeleteBackup(backup)}
                              >
                                删除
                              </Button>
                            </Space>
                          </List.Item>
                        );
                      }}
                      pagination={{
                        pageSize: 5,
                        showTotal: (total, range) => 
                          `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                      }}
                    />
                  </Spin>
                </div>
              )
            },
            {
              key: 'logs',
              label: (
                <span>
                  <FileTextOutlined />
                  系统日志
                </span>
              ),
              children: (
                <div>
                  {/* 日志操作 */}
                  <div className="flex justify-between items-center mb-4">
                    <Space>
                      <Select
                        value={logLevel}
                        onChange={setLogLevel}
                        style={{ width: 120 }}
                      >
                        <Option value="all">全部级别</Option>
                        <Option value="info">信息</Option>
                        <Option value="warning">警告</Option>
                        <Option value="error">错误</Option>
                      </Select>
                      <Select
                        value={logModule}
                        onChange={setLogModule}
                        style={{ width: 120 }}
                      >
                        <Option value="all">全部模块</Option>
                        <Option value="auth">认证</Option>
                        <Option value="system">系统</Option>
                        <Option value="database">数据库</Option>
                      </Select>
                    </Space>
                    <Space>
                      <Button icon={<DownloadOutlined />} onClick={handleExportLogs}>
                        导出日志
                      </Button>
                      <Button danger icon={<ClearOutlined />} onClick={handleClearLogs}>
                        清空日志
                      </Button>
                    </Space>
                  </div>

                  {/* 日志列表 */}
                  <Spin spinning={loading}>
                    <List
                      dataSource={logs}
                      locale={{
                        emptyText: <Empty description="暂无系统日志" />
                      }}
                      renderItem={(log, index) => {
                        const levelConfig = {
                          info: { color: 'blue', icon: '🔵' },
                          warning: { color: 'orange', icon: '🟡' },
                          error: { color: 'red', icon: '🔴' }
                        };
                        const config = levelConfig[log.level] || { color: 'default', icon: '⚪' };
                        
                        return (
                          <List.Item key={log.id || index}>
                            <List.Item.Meta
                              avatar={<span style={{ fontSize: '16px' }}>{config.icon}</span>}
                              title={
                                <Space>
                                  <Tag color={config.color}>{log.level.toUpperCase()}</Tag>
                                  <span>{log.message}</span>
                                </Space>
                              }
                              description={
                                <Space>
                                  <span>模块: {log.module}</span>
                                  {log.user && <span>用户: {log.user}</span>}
                                  <span>时间: {dayjs(log.createdAt).format('YYYY-MM-DD HH:mm:ss')}</span>
                                </Space>
                              }
                            />
                          </List.Item>
                        );
                      }}
                      pagination={{
                        current: logPagination.page,
                        pageSize: logPagination.limit,
                        total: logPagination.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        onChange: (page, pageSize) => {
                          loadLogs(page, pageSize);
                        },
                        onShowSizeChange: (current, size) => {
                          loadLogs(1, size);
                        },
                        showTotal: (total, range) => 
                          `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                      }}
                    />
                  </Spin>
                </div>
              )
            }
          ]}
        />
      </Card>

      {/* 用户编辑弹窗 */}
      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={userModalOpen}
        onCancel={() => {
          setUserModalOpen(false);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveUser}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="nickname"
            label="昵称"
            rules={[{ required: true, message: '请输入昵称' }]}
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>

          {!editingUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}

          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              <Option value="admin">管理员</Option>
              <Option value="guest">游客</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="active">激活</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>

          <div className="flex justify-end space-x-2">
            <Button onClick={() => setUserModalOpen(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              {editingUser ? '更新' : '创建'}
            </Button>
          </div>
        </Form>
      </Modal>

      {/* 联系人编辑弹窗 */}
      <Modal
        title={
          <div className="flex items-center space-x-2">
            <ContactsOutlined className="text-blue-600" />
            <span>{editingContact ? '编辑联系人' : '新增联系人'}</span>
            <Tag color="blue">{contacts.length + (editingContact ? 0 : 1)}/2</Tag>
          </div>
        }
        open={contactModalOpen}
        onCancel={() => {
          setContactModalOpen(false);
          contactForm.resetFields();
        }}
        footer={null}
        width={600}
        className="contact-modal"
      >
        <div className="mb-4 p-3 bg-blue-50 rounded-lg border border-blue-200">
          <div className="text-sm text-blue-700">
            <div className="font-medium mb-1">💡 联系人管理说明</div>
            <div>• 最多可添加2个联系人，用于前台联系模态框展示</div>
            <div>• 建议添加主要业务联系人，如销售经理、客服专员等</div>
            <div>• 微信二维码为必填项，用于客户扫码添加微信</div>
          </div>
        </div>
        
        <Form
          form={contactForm}
          layout="vertical"
          onFinish={handleSaveContact}
          autoComplete="off"
          className="space-y-4"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
                hasFeedback
              >
                <Input 
                  placeholder="请输入姓名" 
                  prefix={<UserOutlined className="text-gray-400" />}
                  size="large"
                  className="transition-all duration-200 hover:border-blue-400 focus:border-blue-500 focus:shadow-sm"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="position"
                label="职位"
                rules={[{ required: true, message: '请输入职位' }]}
                hasFeedback
              >
                <Input 
                  placeholder="如：销售经理、客服专员" 
                  size="large"
                  className="transition-all duration-200 hover:border-blue-400 focus:border-blue-500 focus:shadow-sm"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="联系电话"
                rules={[
                  { required: true, message: '请输入联系电话' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
                ]}
                hasFeedback
              >
                <Input 
                  placeholder="请输入手机号码" 
                  prefix={<PhoneOutlined className="text-gray-400" />}
                  size="large"
                  className="transition-all duration-200 hover:border-blue-400 focus:border-blue-500 focus:shadow-sm"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="wechat"
                label="微信号（可选）"
              >
                <Input 
                  placeholder="请输入微信号" 
                  prefix={<WechatOutlined className="text-gray-400" />}
                  size="large"
                  className="transition-all duration-200 hover:border-blue-400 focus:border-blue-500 focus:shadow-sm"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="wechatQr"
            label="微信二维码"
            rules={[{ required: true, message: '请上传微信二维码' }]}
          >
            <div className="flex flex-col items-center">
              <Upload
                name="wechatQr"
                listType="picture-card"
                className="qr-uploader"
                showUploadList={false}
                beforeUpload={(file) => {
                  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                  if (!isJpgOrPng) {
                    message.error('只能上传 JPG/PNG 格式的图片!');
                    return false;
                  }
                  const isLt2M = file.size / 1024 / 1024 < 2;
                  if (!isLt2M) {
                    message.error('图片大小不能超过 2MB!');
                    return false;
                  }
                  return false; // 阻止自动上传，使用本地预览
                }}
                fileList={[]}
                onChange={async (info) => {
                  if (info.file && info.file.originFileObj) {
                    try {
                      const uploadResult = await uploadApi.uploadFile(info.file.originFileObj as File, 'image');
                      contactForm.setFieldsValue({ wechatQr: uploadResult.url });
                      message.success('微信二维码上传成功');
                    } catch (error) {
                      message.error('微信二维码上传失败');
                    }
                  }
                }}
              >
                {contactForm.getFieldValue('wechatQr') ? (
                  <img src={contactForm.getFieldValue('wechatQr')} alt="wechat-qr" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                ) : (
                  <div className="flex flex-col items-center justify-center h-full">
                    <QrcodeOutlined className="text-2xl text-gray-400 mb-1" />
                    <div className="text-xs text-gray-500">上传二维码</div>
                  </div>
                )}
              </Upload>
              <div className="text-xs text-gray-500 text-center mt-2">
                <div>建议尺寸：200x200像素</div>
                <div>支持：JPG、PNG，不超过2MB</div>
              </div>
            </div>
          </Form.Item>

          <Form.Item
            name="description"
            label="个人简介（可选）"
          >
            <TextArea 
              rows={3} 
              placeholder="请输入个人简介，如工作经验、专业领域等" 
              showCount
              maxLength={100}
              className="transition-all duration-200 hover:border-blue-400 focus:border-blue-500 focus:shadow-sm"
            />
          </Form.Item>

          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            <Button 
              size="large" 
              onClick={() => setContactModalOpen(false)}
            >
              取消
            </Button>
            <Button 
              type="primary" 
              size="large" 
              htmlType="submit" 
              loading={contactLoading}
              icon={editingContact ? <EditOutlined /> : <PlusOutlined />}
            >
              {editingContact ? '更新联系人' : '创建联系人'}
            </Button>
          </div>
        </Form>
      </Modal>


    </div>
  );
};

export default SystemPage;